import {captcha, login} from '@/service'
import {Message} from 'element-ui'

/**
 * 处理Ajax返回数据
 * @author 张晓东
 * @param {Object} source 资源数据
 * @param {String} key vuex key
 * @param {Function} commit MTS commit
 */
const handle = (source, key, commit) => {
  let {data, code, msg} = source
  if (code === 200) {
    commit("SET_STATE", {key: key, value: data})
  } else {
    Message({
      showClose: true,
      message: msg,
      type: 'error'
    })
    Promise.reject(msg)
  }
}


export default {
  namespaced: true,
  state() {
    return {
      captcha: '',
      token: ''
    }
  },
  getter: {},

  /**
   * 零件基础
   */
  mutations: {
    /**
     * 状态设置器
     * @author 张晓东
     * @param state
     * @param {Object} payload  key:建，value:值，isStorage=true同时设置缓存，isStorage=false不设置缓存
     * @constructor
     */
    SET_STATE(state, payload) {
      state[payload.key] = payload.value
      if (payload.isStorage) {
        localStorage.setItem(payload.key, payload.value)
      }
    }
  },

  /**
   * 功能组合器，最终在试图触发
   */
  actions: {
    /**
     * 获取图片验证码
     * @author 张晓东
     * @param commit
     * @returns {Promise<void>}
     * @constructor
     */
    async GET_CAPTCHA({commit}) {
      let source = await captcha()
      handle(source, 'captcha', commit)
    },

    /**
     * 登陆
     * @author 张晓东
     * @param commit
     * @param payload payload.params ajax请求参数, payload.params 成功回调， payload.fail 失败回调
     * @constructor
     */
    LOGIN({commit}, payload) {
      login(payload.params).then((source) => {
        if (source.code === 200) {
          commit("SET_STATE", {key: 'token', value: source.data, isStorage: true})
          payload.success && payload.success()

        } else {
          Message({
            showClose: true,
            message: source.msg,
            type: 'error'
          })
          payload.fail && payload.fail(source)
          Promise.reject(source.msg)
        }
      }, err => {
        payload.fail && payload.fail(err)
      })
    }
  }
}
